<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            let tree = {
                val: 1,
                children: [
                    { val: 2, children: [{ val: 5 }, { val: 6 }, { val: 7 }] },
                    { val: 3, children: [{ val: 8 }] },
                    { val: 4 },
                ],
            }
            let result = []
            function dfs(root, path) {
                path.push(root.val)
                //其实这里也是判断节点是否存在
                let children = root.children || []
                if (!children.length) {
                    return result.push([...path])
                }
                for (let i = 0; i < children.length; i++) {
                    dfs(children[i], path)
                    path.pop()
                }
            }
            dfs(tree, [])
            console.log(result)

            //方式②注意，这种方式必须在初始化的时候把根节点带上
            function treePath(root) {
                if (!root) return []
                const result = []
                function preOrder(root, path) {
                    //确定终止条件，子节点不存在。即遍历完该条路径
                    let children = root.children || []
                    if (!children.length) {
                        return result.push([...path])
                    }
                    for (let i = 0; i < children.length; i++) {
                        path.push(children[i].val)
                        preOrder(children[i], path)
                        path.pop()
                    }
                }
                preOrder(root, [root.val])
                console.log(result)
            }
            /*
      如果通过children.length来return
      path:[1,2] 然后dfs(5,[1,2])这时候children.length不存在了，只能return了。结果就会少了一层
      所以难点在于何时return。
      但是如果通过判断该节点是否存在来return，可以进入5，但是child.length这时候无法进入循环，也无法return

      */
        </script>
    </body>
</html>
